package io.github.lee.jel.ui.main.media

import android.app.Application
import android.util.Log
import androidx.lifecycle.LifecycleOwner
import com.chad.library.adapter4.BaseQuickAdapter
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.core.vm.BaseRefreshViewModel
import io.github.lee.jel.domain.po.JellyfinSession
import io.github.lee.core.vm.err.NoMoreDataException
import io.github.lee.jel.manager.JellyfinSessionManager
import io.github.lee.jel.manager.JellyfinSessionWatcher
import io.github.lee.jel.repository.JellyfinSessionRepository
import javax.inject.Inject

@HiltViewModel
class MainMediaVM @Inject constructor(
    application: Application,
    private val repo: JellyfinSessionRepository
) : BaseRefreshViewModel<JellyfinSession>(application) {

    private val watcher = object : JellyfinSessionWatcher {
        override fun onSessionChange(session: JellyfinSession) {
            Log.e("TAG", "watcher - $session")
            queryLocalAllSession()
        }
    }

    override fun onCreateAdapter(): BaseQuickAdapter<JellyfinSession, *> = MainMediaAdapter()

    //===Desc:=============================================================


    override fun onRefreshOrLoadMore(isRefresh: Boolean) {
        super.onRefreshOrLoadMore(isRefresh)
        queryLocalAllSession()
    }

    private fun queryLocalAllSession() {
        val list = repo.queryAll()

        if (list.isEmpty()) {
            empty(NoMoreDataException(mContext))
        } else {
            submitList(list)
            refreshSuccess()
        }
    }

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        JellyfinSessionManager.registerWatcher(watcher)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        JellyfinSessionManager.unregisterWatcher(watcher)
    }

    fun deleteSession(session: JellyfinSession) {
        repo.delete(session)
        adapter.remove(session)
        if (adapter.items.isEmpty()) {
            empty()
        }
    }

}